package com.example.myapplication.test;
import redis.clients.jedis.Jedis;

public class RedisClient {
    private Jedis jedis;

    public RedisClient(String host, int port) {
        jedis = new Jedis(host, port);
    }

    public boolean requestToken(String key, int rate, int capacity, int requested) {
        String luaScript = "local key = KEYS[1] " +
                "local rate = tonumber(ARGV[1]) " +
                "local capacity = tonumber(ARGV[2]) " +
                "local now = tonumber(ARGV[3]) " +
                "local requested = tonumber(ARGV[4]) " +
                "local last_tokens = tonumber(redis.call('get', key .. '.tokens')) " +
                "local last_refreshed = tonumber(redis.call('get', key .. '.timestamp')) " +
                "if last_tokens == nil then " +
                "last_tokens = capacity " +
                "last_refreshed = now " +
                "end " +
                "local delta = math.max(0, now - last_refreshed) " +
                "local new_tokens = math.min(capacity, last_tokens + (delta * rate)) " +
                "local allowed = new_tokens >= requested " +
                "local new_timestamp = now " +
                "if allowed then " +
                "new_tokens = new_tokens - requested " +
                "redis.call('setex', key .. '.tokens', 60, new_tokens) " +
                "redis.call('setex', key .. '.timestamp', 60, new_timestamp) " +
                "else " +
                "redis.call('setex', key .. '.tokens', 60, new_tokens) " +
                "redis.call('setex', key .. '.timestamp', 60, new_timestamp) " +
                "end " +
                "return allowed ";

        long now = System.currentTimeMillis() / 1000;
        Object result = jedis.eval(luaScript, 1, key, String.valueOf(rate), String.valueOf(capacity), String.valueOf(now), String.valueOf(requested));
        return (long) result == 1;
    }
}
